const router = require('koa-router')()
router.prefix('/users')

const usersService = require('../../services/users');

const msgModule = require('../../common/msg');
const Result = require('../../common/Result');

router.post('/list', async (ctx, next) => {
  let param = ctx.request.body;
  try {
    const data = await usersService.list(param);
    ctx.body = Result.success(data, msgModule.querySuccess);
  } catch (error) {
    ctx.body = Result.error(error, msgModule.queryError);
  }
});

router.post('/edit', async (ctx, next) => {
  let param = ctx.request.body;
  try {
    const usersData = await usersService.edit(param);
    if (usersData) {
      ctx.body = Result.success(usersData, msgModule.editSuccess);
    } else {
      ctx.body = Result.fail(usersData, msgModule.editError);
    }
  } catch (error) {
    ctx.body = Result.error(error, msgModule.editError);
  }
})

router.get('/byId', async (ctx, next) => {
  let param = ctx.request.query;
  try {
    const usersData = await usersService.byId(param._id);
    if (usersData._id) {
      ctx.body = Result.success(usersData, msgModule.querySuccess);
    } else {
      ctx.body = Result.fail({}, msgModule.queryError);
    }
  } catch (error) {
    ctx.body = Result.error(error, msgModule.queryError);
  }
});

module.exports = router